package com.maybach.workflow.core.processor.impl;


import com.maybach.workflow.common.api.WorkFlowContext;
import com.maybach.workflow.common.api.enums.FlowStateEnum;
import com.maybach.workflow.common.api.node.BaseNode;
import com.maybach.workflow.common.model.FlowDO;
import com.maybach.workflow.core.config.parser.NodeParser;

import java.util.List;

/**
 * Created by houenxun on 15/8/13.
 */
public class StartProcessor extends AbstractProcessor{


    @Override
    public List<BaseNode> getNextNodes(WorkFlowContext workFlowContext) {
        workFlowContext.setThisNode(workFlowContext.getThisFlowChain().getBaseNode(NodeParser.NODE_NAME_START));
        return super.getCommonNextNodes(workFlowContext);
    }

    @Override
    public boolean runIn(WorkFlowContext workFlowContext) {
        // 无条件转移直接流出
        this.runOut(workFlowContext);
        return true;
    }

    @Override
    public void runOut(WorkFlowContext workFlowContext) {
        FlowDO flowDO =createFlowDO(workFlowContext);
        workFlowContext.setThisFlow(flowDO);
        BaseNode baseNode = workFlowContext.getThisFlowChain().getBaseNode(NodeParser.NODE_NAME_START);
        workFlowContext.setThisNode(baseNode);
        super.noPersistRunOut(workFlowContext);
    }

    private FlowDO createFlowDO(WorkFlowContext workFlowContext) {
        // 又是片段
        if(null != workFlowContext.getThisFlow()){
            return workFlowContext.getThisFlow();
        }
        //flowDAO.delByOrderId(workFlowContext.getBizId());
        FlowDO flowDO = new FlowDO();
        flowDO.setBizId(workFlowContext.getBizId());
        flowDO.setBizType(workFlowContext.getBizType());
        flowDO.setCreateUserId(this.securityService.getUserId());
        flowDO.setFlowState(FlowStateEnum.init.getStatus());
        flowDO.setFlowName(workFlowContext.getFlowChain().getName());
        flowDO.setFlowVersion(workFlowContext.getFlowChain().getVersion());
        flowRepository.createFlow(flowDO);
        return flowDO;
    }
}
